package com.banksoft.admin.controller;

import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.entity.UserAddress;
import com.banksoft.admin.service.BaseService;
import com.banksoft.admin.service.UserAddressService;
import com.banksoft.admin.service.UserService;
import com.banksoft.common.BaseController;
import com.banksoft.common.ConfigHelper;
import com.banksoft.common.PageInfo;
import com.banksoft.util.DateUtil;
import com.banksoft.util.MD5Util;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by vanjoger on 2016/12/28.
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    BaseService baseService;
    @Autowired
    UserService userService;
    @Autowired
    UserAddressService userAddressService;


    @RequestMapping("/list")
    public String list(String type,Model model){
        model.addAttribute("type",type);
        return "user/user_list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public Object listData(String nickName,String account,String userName,String startDate,String endDate,String type,String status,PageInfo pageInfo){
        Map<String,Object> map = new HashMap<>();
        String[] types = new String[]{type};
        map.put("type",types);
        map.put("status",status);
        map.put("account",account);
        map.put("userName",userName);
        map.put("isMember","1");
        if(StringUtil.isNotNull(nickName))
            map.put("nickName",nickName);
        if(StringUtil.isNotNull(startDate))
            map.put("startDate", DateUtil.getLongFormStrDate(startDate));
        if(StringUtil.isNotNull(endDate))
            map.put("endDate",DateUtil.getLongFormStrDate(endDate));
        pageInfo.setParams(map);

        pageInfo = this.page(UserDao.class,pageInfo);

        List<User> list = pageInfo.getResult();
        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                List<UserAddress> addressList = userAddressService.listByUserId(user.getId());
                if(StringUtil.isNotEmpty(addressList)){
                    UserAddress address = addressList.get(0);
                    user.setNickName(address.getUserName());
                    if(!StringUtil.isNotNull(user.getMobile())){
                        user.setMobile(address.getTelephone());
                    }else{
                        user.setMobile(user.getMobile()+"/"+address.getTelephone());
                    }
                }
                if(StringUtil.isNotNull(user.getRecommendId())) {
                    User upuser = baseService.findById(UserDao.class,user.getRecommendId());
                    if(upuser!=null){
                        user.setRecommendId(upuser.getNickName()+"("+upuser.getAccount()+")");
                    }else{
                        user.setRecommendId("");
                    }
                }
                List<User> subList = this.userService.listByRecommendId(user.getId());
                user.setSubSize(subList!=null?subList.size():0);
            }
        }
        pageInfo.setResult(list);

        return this.getPageResult(pageInfo);
    }


    /**
     * 得到账号
     * @return
     */
    private String getMemberAccount(){
        String account = StringUtil.getRandom(8);
        List<User> list = this.userService.findByAccount(account);
        if(StringUtil.isNotEmpty(list)){
            return getMemberAccount();
        }else{
            return account;
        }
    }

    @RequestMapping("/beforeEdit")
    public String beforeEdit(String id,Model model){
        if(StringUtil.isNotNull(id)){
            User user = this.baseService.findById(UserDao.class,id);
            if(StringUtil.isNotNull(user.getRecommendId())){
                User upperUser = baseService.findById(UserDao.class,user.getRecommendId());
                if(upperUser!=null)
                    model.addAttribute("upper",upperUser.getAccount());
            }
            model.addAttribute("data",user);
            model.addAttribute("account",user.getAccount());
        }else{
            model.addAttribute("account",getMemberAccount());
        }
        return "user/user_edit";
    }

    @RequestMapping("/save")
    @ResponseBody
    public JSONObject save(User user){
        try {
            if(StringUtil.isNotNull(user.getId())){
               this.baseService.update(UserDao.class,user);
            }else{
                user.setType(MemberType.Customer.name());
                user.setId(UUIDFactory.random());
                user.setCreateTime(new Date().getTime());
                String initPwd = ConfigHelper.GetInstance().GetConfig("Init_Pwd");
                user.setPassword(MD5Util.getMD5ofStr(initPwd));
                userService.saveUser(user);
            }
            return this.FmtResult(true,"保存成功",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"保存失败",null);
    }

    @RequestMapping("/resetPwd")
    @ResponseBody
    public JSONObject resetPwd(String id){
        try {
            User user = this.baseService.findById(UserDao.class,id);
            if(user!=null){
                String initPwd = ConfigHelper.GetInstance().GetConfig("Init_PWd");
                user.setPassword(MD5Util.getMD5ofStr(initPwd));
                this.baseService.update(UserDao.class,user);
                return this.FmtResult(true,"密码重置成功",null);
            }
            return this.FmtResult(true,"没有找到数据",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"重置密码失败",null);
    }


}
